package com.work.yshop.mvp.model;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.work.yshop.model.Product;
import com.work.yshop.provider.ProductProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页数据模型，负责从数据库获取商品数据
 */
public class HomeModel {
    private static final String TAG = "HomeModel";
    
    private Context context;
    
    public HomeModel(Context context) {
        this.context = context.getApplicationContext();
    }
    
    /**
     * 获取所有商品
     */
    public List<Product> getAllProducts() {
        List<Product> products = new ArrayList<>();
        
        try {
            Cursor cursor = context.getContentResolver().query(
                    ProductProvider.CONTENT_URI,
                    null,
                    null,
                    null,
                    null
            );
            
            if (cursor != null) {
                try {
                    Log.d(TAG, "查询结果数量: " + cursor.getCount());
                    
                    while (cursor.moveToNext()) {
                        Product product = getProductFromCursor(cursor);
                        products.add(product);
                    }
                } finally {
                    cursor.close();
                }
            } else {
                Log.w(TAG, "查询结果为空");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取商品列表失败", e);
        }
        
        return products;
    }
    
    /**
     * 根据分类获取商品
     */
    public List<Product> getProductsByCategory(String category) {
        List<Product> products = new ArrayList<>();
        
        try {
            Cursor cursor = context.getContentResolver().query(
                    ProductProvider.CONTENT_URI,
                    null,
                    category != null ? "category = ?" : null,
                    category != null ? new String[]{category} : null,
                    null
            );
            
            if (cursor != null) {
                try {
                    while (cursor.moveToNext()) {
                        Product product = getProductFromCursor(cursor);
                        products.add(product);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取分类商品失败", e);
        }
        
        return products;
    }
    
    /**
     * 获取某个商品详情
     */
    public Product getProductById(int productId) {
        Product product = null;
        
        try {
            Uri uri = Uri.withAppendedPath(ProductProvider.CONTENT_URI, String.valueOf(productId));
            Cursor cursor = context.getContentResolver().query(
                    uri,
                    null,
                    null,
                    null,
                    null
            );
            
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        product = getProductFromCursor(cursor);
                    }
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "获取商品详情失败", e);
        }
        
        return product;
    }
    
    /**
     * 从Cursor中提取商品数据
     */
    private Product getProductFromCursor(Cursor cursor) {
        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
        String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
        String description = cursor.getString(cursor.getColumnIndexOrThrow("description"));
        double price = cursor.getDouble(cursor.getColumnIndexOrThrow("price"));
        double originalPrice = cursor.getDouble(cursor.getColumnIndexOrThrow("original_price"));
        String unit = cursor.getString(cursor.getColumnIndexOrThrow("unit"));
        int salesCount = cursor.getInt(cursor.getColumnIndexOrThrow("sales_count"));
        String imageUrl = cursor.getString(cursor.getColumnIndexOrThrow("image_url"));
        
        Product product = new Product(id, name, description, price, originalPrice, unit, salesCount, imageUrl);
        
        // 获取可选字段
        int stockColumnIndex = cursor.getColumnIndex("stock");
        if (stockColumnIndex != -1) {
            product.setStock(cursor.getInt(stockColumnIndex));
        }
        
        int categoryColumnIndex = cursor.getColumnIndex("category");
        if (categoryColumnIndex != -1) {
            product.setCategory(cursor.getString(categoryColumnIndex));
        }
        
        int shopIdColumnIndex = cursor.getColumnIndex("shop_id");
        if (shopIdColumnIndex != -1) {
            product.setSellerId(cursor.getInt(shopIdColumnIndex));
        }
        
        return product;
    }
} 